import type { UserInfo } from '@/api/user/type'
import { ref } from 'vue'
import { LOCAL_JWT_TOKEN_CACHE_KEY, LOCAL_TENANT_CACHE_KEY } from '@/constants'
import { store } from '@/stores'
import { localStore } from '@/utils/cache/storage'
import { defineStore } from 'pinia'

/**
 * 定义用户状态管理
 */
export const useUserStore = defineStore('user', () => {
  // state
  const userInfo = ref<null | UserInfo>(null) // 用户数据
  const isLogin = ref(false) // 是否登录
  const token = ref('') // 用户token
  const tenant = ref('') // 租户

  // 设置用户信息
  const setUserInfo = (data: null | UserInfo) => {
    userInfo.value = data
  }

  // 设置用户信息
  const setIsLogin = (_isLogin: boolean) => {
    isLogin.value = _isLogin
  }

  // 设置token
  const setToken = (_token: string) => {
    localStore.set(LOCAL_JWT_TOKEN_CACHE_KEY, _token)
    token.value = _token
  }

  // 获取token
  const getToken = () => {
    return token.value || localStore.get(LOCAL_JWT_TOKEN_CACHE_KEY)
  }

  // 设置token
  const setTenant = (_tenant: string) => {
    localStore.set(LOCAL_TENANT_CACHE_KEY, _tenant)
    tenant.value = _tenant
  }

  // 获取租户
  const getTenant = () => {
    return tenant.value || localStore.get(LOCAL_TENANT_CACHE_KEY)
  }

  return {
    setUserInfo,
    setIsLogin,
    setToken,
    isLogin,
    token,
    userInfo,
    getToken,
    setTenant,
    getTenant
  }
})

// 需要在设置之外使用
export const useUserStoreWithOut = () => {
  return useUserStore(store)
}
